﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.Networking;

namespace BToolkit
{
    public class SceneLoading : MonoBehaviour
    {

        public Slider slider;
        public Text text;
        public float delay = 0.5f;
        public bool fakeLoading;
        static string targetLevelName;
        static string sceneAssetBundlePath;
        UnityWebRequest assetBundleRequest;
        float fakeProgress;
        static AssetBundle landAndSeaAssetBundle;

        IEnumerator Start()
        {
            yield return new WaitForSeconds(delay);
            if (sceneAssetBundlePath == null)
            {
                StartCoroutine(LoadSceneAsynchronously());
            }
            else
            {
                StartCoroutine(LoadSceneAssetBundle());
            }
        }

        IEnumerator LoadSceneAsynchronously()
        {
            AsyncOperation operation = SceneManager.LoadSceneAsync(targetLevelName);
            operation.allowSceneActivation = false;
            if (fakeLoading)
            {
                fakeProgress = 0;
                while (true)
                {
                    fakeProgress = Mathf.Clamp01(fakeProgress + Random.Range(0.1f, 0.3f) * Time.deltaTime);
                    if (fakeProgress >= 0.9f)
                    {
                        if (operation.progress >= 0.9f)
                        {
                            operation.allowSceneActivation = true;
                            UpdateUI(1);
                            yield return null;
                            break;
                        }
                    }
                    UpdateUI(fakeProgress);

                    yield return null;
                }
            }
            else
            {
                while (!operation.isDone)
                {
                    if (operation.progress >= 0.9f)
                    {
                        UpdateUI(1);
                        operation.allowSceneActivation = true;
                    }
                    else
                    {
                        var progress = Mathf.Clamp01(operation.progress / 0.9f);
                        UpdateUI(progress);
                    }
                    yield return null;
                }
            }
        }

        IEnumerator LoadSceneAssetBundle()
        {
            if (!landAndSeaAssetBundle)
            {
                assetBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(sceneAssetBundlePath);
                yield return assetBundleRequest.SendWebRequest();
                if (assetBundleRequest.error != null)
                {
                    Debug.Log("从AssetBundle[" + sceneAssetBundlePath + "]加载场景" + targetLevelName + "失败");
                    yield break;
                }
                landAndSeaAssetBundle = (assetBundleRequest.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
            }
            SceneManager.LoadScene(targetLevelName);
        }

        void Update()
        {
            if (assetBundleRequest != null)
            {
                UpdateUI(assetBundleRequest.downloadProgress);
            }
        }

        void UpdateUI(float progress)
        {
            if (slider)
            {
                slider.value = progress;
            }
            if (text)
            {
                text.text = (int)(progress * 100) + "%";
            }
        }

        /// <summary>
        /// assetBundlePath传空则从本地切换场景，否则加载AssetBundle里的场景
        /// </summary>
        public static void LoadScene(string levelName, string assetBundlePath = null)
        {
            SceneLoading.targetLevelName = levelName;
            SceneLoading.sceneAssetBundlePath = assetBundlePath;
            SceneManager.LoadScene("Loading");
        }

    }
}